package com.wolfking.jeesite.util;

import com.wolfking.jeesite.event.DefaultEvent;
import com.wolfking.jeesite.event.AbstractSignEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

@Slf4j
public class SignEventUtil {

    public static AbstractSignEvent createSignEvent(HttpServletRequest request, Class<? extends AbstractSignEvent> eventClass, Integer userId) {
        AbstractSignEvent abstractSignEvent = new DefaultEvent("signAspect");
        if (eventClass.equals(AbstractSignEvent.class)) {
            return abstractSignEvent;
        }
        try {
            Constructor<?> constructor = eventClass.getDeclaredConstructor(Object.class);
            abstractSignEvent = (AbstractSignEvent) constructor.newInstance("signAspect");
        } catch (Exception e) {
            log.warn("", e);
        }
        abstractSignEvent.setUserId(userId);
        if (Objects.nonNull(request)) {
            String[] removeParameters = new String[]{"json", "jsessionid", "tabPageId"};
            abstractSignEvent.setUrl(RequestUtil.getRequestUrl(request, removeParameters));
            abstractSignEvent.setParameters(RequestUtil.getRequestParameters(request));
            for (String parameter : new ArrayList<>(abstractSignEvent.getParameters().keySet())) {
                if (parameter.toLowerCase(Locale.ROOT).contains("password")) {
                    abstractSignEvent.getParameters().put(parameter, "******");
                }
            }
            for (String parameter : removeParameters) {
                abstractSignEvent.getParameters().remove(parameter);
            }
            abstractSignEvent.setHeaders(RequestUtil.getRequestHeaders(request));
            abstractSignEvent.setCookies(RequestUtil.getRequestCookies(request));
            abstractSignEvent.setHttpMethod(request.getMethod().toUpperCase(Locale.ROOT));
        }
        return abstractSignEvent;
    }

    public static AbstractSignEvent createSignEvent(Class<? extends AbstractSignEvent> eventClass, Integer userId) {
        HttpServletRequest request = null;
        ServletRequestAttributes attributes = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes());
        if (Objects.nonNull(attributes)) {
            request = attributes.getRequest();
        }
        return createSignEvent(request, eventClass, userId);
    }
}
